package com.example.demo.service.impl;

import com.example.demo.common.Result;
import com.example.demo.common.ResultCode;
import com.example.demo.pojo.UserEntity;
import com.example.demo.service.UserService;
import com.example.demo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author xukang
 * @date 2021-09-10 15:33
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result register(String username, String account, String realname, Integer age) {
        //查询用户名是否唯一
        //TODO 雪花算法 分布式id
        Result result = new Result(ResultCode.FAIL);
        try {
            int i = userMapper.updateByPrimaryKeySelective(UserEntity.builder().account(account).build());
            if (i > 0) {
                result.setMessage("用户名已存在");
                return result;
            }
            UserEntity userEntity = UserEntity.builder().username(username).age(age).account(account).realname(realname).build();
            userMapper.insert(userEntity);

        } catch (Exception e) {
            log.error("register::{}", e.getMessage());
            return result;
        }
        return new Result(ResultCode.SUCCESS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateById(Long id, UserEntity userEntity) {

        Result result = new Result(ResultCode.FAIL);
        try {

            if (null == userEntity.getId() || ObjectUtils.isEmpty(userMapper.selectByPrimaryKey(userEntity.getId()))) {
                result.setMessage("更新错误,不存在");
                return result;
            }
            userMapper.updateByPrimaryKeySelective(userEntity);
        } catch (Exception e) {
            log.error("getByContion::{}", e.getMessage());
            result.setMessage(e.getMessage());
            return result;
        }

        return new Result();
    }

    @Override
    public Result getByContion(UserEntity userEntity) {
        Result result = new Result(ResultCode.FAIL);
        try {
            if (ObjectUtils.isEmpty(userEntity)) {
                result.setMessage("条件不能为空");
                return result;
            }
            List<UserEntity> userEntities = userMapper.queryByUser(userEntity);
            result = new Result(ResultCode.SUCCESS);
            result.setData(userEntities);
            return result;
        } catch (Exception e) {
            log.error("getByContion::{}", e.getMessage());
            return result;
        }


    }

}
